import datetime
import logging
from idlelib.configdialog import is_int

import jwt
from django.conf import settings
from django.db.models import Count, Max, Min, Sum
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
#分页模块
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
from rest_framework.parsers import JSONParser

from employee.models import employee, bugdata, casedata


#判空的方法
def is_empty(c):
    return c is None or str(c).strip() == ''

# Create your views here.
#添加数据
@api_view(['POST'])
def employee_add(request):
    #解析请求数据
    body = request.data
    name = body.get('name1')
    password = body.get('password')
    gender = body.get('gender')
    age = body.get('age')
    department = body.get('department')
    kpi = body.get('kpi')
    address = body.get('address')


    if is_empty(address):
        # 如果address为空则执行 employee里的数据
        employee(name=name, password=password, gender=gender, age=age, department=department, kpi=kpi).save()
    else:
        #如果address不为空则执行 employee里的数据
        employee(name=name, password=password, gender=gender, age=age, department=department, kpi=kpi,
                 address=address).save()

    return JsonResponse({
        "code":status.HTTP_200_OK,
        "message":"添加数据成功"
    })


#分页
@api_view(['GET'])
def getinfo(request):

    #鉴权代码
    flan,name = checktoken(request)
    if flan is False:
        return JsonResponse({"msg":"未登录，请先登录",'code':status.HTTP_401_UNAUTHORIZED})

    #获取参值
    page = request.GET.get('page')
    pagesize = request.GET.get('pagesize')
    # gender = request.get('gender')
    # department = request.get('department')
    # address = request.get('address')

    # if is_empty(name)and is_empty(gender) is False and is_empty(department) is False and is_empty(address):
    #     allobj = employee.objects.filter(gender=gender,department=department,address=address)
    # elif is_empty(name) is False:
    #     allpbj  = employee.objects.filter(name=name)
    #
    # elif is_empty(name) is True:
    #     allpbj = employee.objects.filter(name=name)

    #先查询出所有的数据对象 is F
    allobj = employee.objects.filter()
    #打印日志
    logging.info(f'查看得到的数据对象{allobj}')
    #对所有数据进行分页处理
    #导入Paginator的包 allobj所有数据对象  pagesize每页有多少个数据
    allpageogj = Paginator(allobj,pagesize)

    #抛异常
    try:
        # 尝试获取指定页码的数据
        singleobj = allpageogj.page(page)
    except PageNotAnInteger:  # 请求页数如说不是整数 则返回第一页的数据
        singleobj = allpageogj.page(1)
    except EmptyPage:   # 请求是页数大于原本的页数 则进入EmptyPage分支
        singleobj = allpageogj.page(allpageogj.num_pages)

    #打印日志
    logging.info(f'查看单页的数据对象:{singleobj}')

    #定义一个空列表，用于存储数据
    lis = []
    #打印日志
    logging.info(f'查看单页的数据对象singleobj.object_list:{singleobj.object_list}')
    #循环
    for item in singleobj.object_list:
        lis.append({
            "id":item.id,
            "name":item.name,
            "password":item.password,
            "gender": "男" if item.gender == 'M' else '女',
            "age":item.age,
            "department":item.department,
            "kpi":item.kpi,
            "address":item.address,
            "createtime":item.createtime,
            'updatetime':item.updatetime,
        })

    #返回
    return JsonResponse({
        'code':status.HTTP_200_OK,
        'data':lis,
        'pageinfo':{
            'page':page,
            'pagesize':pagesize,
            # 'total':allobj.count()
        },
        'items':allobj.count()
    })
import random,string
from django.core.signing import Signer  #签名
from django.core.cache import cache  #缓存
from datetime import timedelta
# 鉴权 产生token的方法
def createtoken(name):
    #产生一个八位的随机字符串
    randomstr = ''.join(random.choices(string.ascii_letters,k=8))
    #对字符串进行签名
    token = Signer().sign(randomstr+name)  #通过+号对字符串进行拼接
    #把token保存到缓存中
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
    #把token返回
    return token


# 登录
@api_view(['POST'])
def login(request):
    data = JSONParser().parse(request)
    name = data.get('name')
    password = data.get('password')

    # #判断
    if employee.objects.filter(name=name).exists() is None:
        return JsonResponse({"msg": "用户或密码错误", "code": status.HTTP_400_BAD_REQUEST})
    obj = employee.objects.get(name=name)
    logging.info(f'查看单个数据对象：{obj}')
    if obj.password != password:
        return JsonResponse({"msg":"密码错误","code":status.HTTP_401_UNAUTHORIZED})

    #调用产生token方法
    token = createtoken(name)
    return JsonResponse({
        "code":status.HTTP_200_OK,
        "msg":"登录成功",
        "token":token,
    })
    #判断
    # dbRes = employee.objects.filter(name=name).values()
    # for i in dbRes:
    #     if i['password'] == password:
    #         # user = UserInfo.objects.get(name=name, password=password)
    #         # 生成jwt token
    #         token = jwt.encode({
    #             'id': i['id'],
    #             'name': i['name'],
    #             'password': i['password'],
    #             'exp': datetime.datetime.now() + datetime.timedelta(days=1)
    #         }, settings.SECRET_KEY, algorithm='HS256')
    #         # 返回token参数
    #         return JsonResponse({"token": token, "message": "登录成功"})
    #         # return JsonResponse({"message":"登录成功"})
    #     else:
    #         return JsonResponse({"message": "登录失败"})

# #解码token
@api_view(['POST'])
def loginbtn_token(request):
    # 验证token
    auth_header = request.headers.get('Authorization','')
    try:
        #检查Authorization header格式第一个参数是不是Bearer+空格
        if not auth_header.startswith('Bearer '):
            return JsonResponse({
                "message":"token格式错误"
            },status=status.HTTP_404_NOT_FOUND)

        #分割成列表去第二个参数
        token = auth_header.split('Bearer ')[1]
        if not token:
            return JsonResponse({
                "message":"token不能为空"
            },status=status.HTTP_404_NOT_FOUND)
        # 解码token
        decode_token = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256')
        return JsonResponse({"token": decode_token})

    except Exception as e:
        return JsonResponse({
            "message": "token验证失败"
        },status=status.HTTP_404_NOT_FOUND)


#鉴权的方法
def checktoken(request):

    #获取前端传过来的token
    requtoken = request.META.get('HTTP_TOKEN')
    logging.info(f'查看前端传过来的token：{requtoken}')
    #判断
    if requtoken is None:
        return False, 'XXXX'
    #校验缓存中token是否存在
    #先做反签名
    untoken = Signer().unsign(requtoken)
    logging.info(f'看看反签名内容：{untoken}')
    name = untoken[8:]
    #校验缓存文件中token，还存在不
    cachetoken = cache.get(f'test_{name}')
    logging.info(f'查看缓存中的token内容:{cachetoken}')

    #判断cachetoken 未None
    if cachetoken is None:
        return False,'XXXX'

    return True,name


# #分组查询
# @api_view(['GET'])
# def groupdata(request):
#     data = employee.objects.values('gender').annotate(num=Count('gender'),minahe=Min('age'),maxage=Max('age'),apisum=Sum('kpi'))
#     logging.info(f'查看到的数据:{data}')
#
#
#     return JsonResponse({
#         "code'":status.HTTP_200_OK,
#         "data:":list(data)
#     })
#
#
# #表关联
# @api_view(['GET'])
# def getbuginfo(request):
#
#     bugobj = bugdata.objects.filter()
#
#     lis = []
#     for i in bugobj:
#         lis.append({
#             "缺陷ID":i.id,
#             "缺陷标题":i.title,
#             "缺陷的状态":i.status,
#             "实际结果": i.actual,
#             "当前指派人":i.assigned,
#             #关联到用例表
#             "用例名称":i.case.casename,
#             "用例状态":i.case.status,
#             "预期结果":i.case.expect
#
#         })
#
#     return JsonResponse({
#         "code":status.HTTP_200_OK,
#         "data":lis
#     })
#
# #bug表关联用例
# @api_view(['GET'])
# def getcaseinfo(request):
#     caseobj = casedata.objects.filter()
#
#     lis = []
#     for i in caseobj:
#         for k in i.bugdata.all():
#             lis.append({
#                 "用例名称": i.casename,
#                 "用例状态": i.status,
#                 "预期结果": i.expect,
#                 # 关联到用例表
#                 "缺陷ID": i.id,
#                 "缺陷标题": k.title,
#                 "缺陷的状态": k.status,
#                 "实际结果": k.actual,
#                 "当前指派人": k.assigned,
#
#
#             })
#
#     return JsonResponse({
#         "code": status.HTTP_200_OK,
#         "data": lis
#     })
#
# @api_view(['POST'])
# def addcase(request):
#     #鉴权
#     flag,name = checktoken(request)
#
#     # 判空
#     if flag is False:
#         return JsonResponse({"message": "未登录无法添加用例"})
#
#
#     #解析前端传送的数据
#     data = JSONParser().parse(request)
#     employeeobj = employee.objects.get(name=name)
#     status = data.get('status')
#     step = data.get('step')
#     expect = data.get('expect')
#     casename = data.get('casename')
#
#     if is_empty(casename) or is_empty(expect):
#         return JsonResponse({"message":"参数不能为空","error":status.HTTP_400_BAD_REQUEST})
#
#     # 判重
#     if casedata.objects.filter(casename=casename).exists() is True:
#         return JsonResponse({"message":"用例已存在"},status.HTTP_404_NOT_FOUND)
#
#     casedata(casename=casename,status=status,step=step,expect=expect,employee=employeeobj).save()
#     return JsonResponse({"code":status.HTTP_200_OK,"msg":"添加成功"})

# @api_view(['GET'])
# def getcase(request):
#     #鉴:权
#     flag,name = checktoken(request)
#     if flag is False:
#         return JsonResponse({"message": "未登录无法添加用例"},status.HTTP_404_NOT_FOUND)
#
#     lis = []
#     #得到所有的用例i对d
#     allaseobj = employee.casedata.all()
#     for i in allaseobj:
#         return JsonResponse({"msg":"200"})

#删除
@api_view(['DELETE'])
def deleteitem(request,itemid):

    flag,name = checktoken(request)
    if flag is False:
        return JsonResponse({"code":status.HTTP_401_UNAUTHORIZED,"msg":"未登录，数据无法删除"})
    employeeobj = employee.objects.get(id=itemid)
    employeeobj.delete()

    return JsonResponse({"code":200,"msg":"删除成功"})

@api_view(['GET'])
def getitemployee(request,itemid):

    # 先查询出所有的数据对象 is F
    allobj = employee.objects.get(id=itemid)

    return JsonResponse({
            "name": allobj.name,
            "gender": "男" if allobj.gender == 'M' else '女',
            "age": allobj.age,
            "department": allobj.department,
            "kpi": allobj.kpi,
            "address": allobj.address,
    })

#修改
@api_view(['PUT'])
def uodateemployee(request,itemid):
    #解析数据
    data = JSONParser().parse(request)

    gender = data.get('gender')
    age = data.get('age')
    department = data.get('department')
    kpi = data.get('kpi')
    address = data.get('address')

    item = employee.objects.get(name__contains=itemid)

    item.gender = gender
    item.age = age
    item.department = department
    item.kpi = kpi
    item.address = address
    #保存
    item.save()

    return JsonResponse({"msg":"修改成功","code":status.HTTP_200_OK})


@api_view(['GET'])
def chaxun(request):

    # user = employee.objects.filter(name__contains=itemid)


    name = request.GET.get('title')
    xing = request.GET.get('xing')
    group = request.GET.get('group')

    if xing == '男':
        xing='M'
    elif xing =='女':
        xing='F'

    page = request.GET.get('page')
    pagesize = request.GET.get('pagesize')
    dic = {}
    if is_empty(name) is False:
        dic['name_contains'] = name

    if is_empty(group) is False:
        dic['group'] = group

    if is_empty(xing) is False:
        dic['xing'] = xing

    allobi = employee.objects.filter(**dic)

    # allobi = None
    # if is_empty(name) and is_empty(xing) and is_empty(group):
    #     allobi = employee.objects.filter()
    #
    # elif is_empty(name) is False and is_empty(xing) is False and is_empty(group) is False:
    #     allobi = employee.objects.filter(name__contains=name,gender=xing)
    # elif is_empty(name) and is_empty(xing) is False and is_empty(group):
    #     allobi = employee.objects.filter(gender=xing)
    # elif is_empty(name) is False and is_empty(xing) and is_empty(group):
    #     allobi = employee.objects.filter(name__contains=name)
    #

    # logging.info(f'查看得到的数据{allobi}')
    allpageobj = Paginator(allobi,pagesize)
    try:
        # 尝试获取指定页码的数据
        singleobj = allpageobj.page(page)
    except PageNotAnInteger:  # 请求页数如说不是整数 则返回第一页的数据
        singleobj = allpageobj.page(1)
    except EmptyPage:  # 请求是页数大于原本的页数 则进入EmptyPage分支
        singleobj = allpageobj.page(allpageobj.num_pages)

    logging.info(f'查看单页的数据{singleobj}')
    lis = []
    logging.info(f'查看单页的数据对象obj_list{singleobj.object_list}')
    # 循环
    for item in singleobj.object_list:
        lis.append({
            "id": item.id,
            "name": item.name,
            "password": item.password,
            "gender": "男" if item.gender == 'M' else '女',
            "age": item.age,
            "department": item.department,
            "kpi": item.kpi,
            "address": item.address,
            "createtime": item.createtime,
            'updatetime': item.updatetime,
        })

    # 返回
    return JsonResponse({
        'code': status.HTTP_200_OK,
        'data': lis,
        'items': allobi.count(),
        'pageinfo': {
            'page': page,
            'pagesize': pagesize,
            # 'total':allobj.count()
        }
    })
@api_view(['GET'])
def getdepartments(request):

    #分组查询
    departments = employee.objects.values('department').annotate(itemid=max('id'))
    logging.info(f'查看分组后的数据:{departments}')

    #空列表
    lis = [{'value': ' ', 'label': '请先选择' }]

    #循环
    for item in departments:
        lis.append({
            'value':item.get('department'),
            'label':item.get('department')
        })
    return JsonResponse({
        "code":status.HTTP_200_OK,
        "data":lis
    })
